package tpoo.client.controllers.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandlerListener;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;

import tpoo.client.ui.dialogs.AddContactDialog;
import tpoo.common.services.UserService;
import tpoo.common.services.exceptions.ServiceException;
import tpoo.common.services.utils.ServiceAdmin;
import tpoo.common.services.utils.ServiceConstants;
import tpoo.common.utils.UserSession;

public class AddContactHandler 
extends AbstractHandler implements ServiceConstants {
	
	/**
	 * the command has been executed, so extract extract the needed information
	 * from the application context.
	 */
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
		
		AddContactDialog d = new AddContactDialog(window.getShell());
		
		if (d.open() == IDialogConstants.OK_ID){
			UserService us;
			try {
				us = (UserService) ServiceAdmin.getService(USER_SERVICE);
				us.addContact(UserSession.getInstance().getUser(), d.getContactName());
			} catch (ServiceException e) {
				e.printStackTrace();
				throw new ExecutionException(e.getMessage());
			}
			
		}
		return null;
			
	}
}